//
//  ListUniversitiesViewController.m
//  Edumap
//
//  Created by 辰领科技 on 16/8/2.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "ListUniversitiesViewController.h"
#import "AreaTableViewCell.h"
#import "SchoolTableViewCell.h"
#import "SchoolProfileViewController.h"

static NSString *leftCellIdentifier = @"AreaTableViewCell";
static NSString *rightCellIdentifier = @"SchoolTableViewCell";

@interface ListUniversitiesViewController ()
<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *leftTAbelView;
@property (strong, nonatomic) IBOutlet UITableView *rightTAbelView;


@property (strong, nonatomic) NSMutableArray *leftArray;
@property (strong, nonatomic) NSMutableArray *rightArray;

@property (weak, nonatomic) IBOutlet UITextField *searchField;

@property (assign, nonatomic) NSInteger count;
@property (strong, nonatomic) NSString *AId;
@end

@implementation ListUniversitiesViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.rightTAbelView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _rightArray = [NSMutableArray array];
    _count = 0;
    [self area];
    [self initViewLayout];
    [self addRefreshing];
}

- (void)initViewLayout {
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    [self.leftTAbelView registerNib:[UINib nibWithNibName:leftCellIdentifier bundle:nil] forCellReuseIdentifier:leftCellIdentifier];
    self.leftTAbelView.delegate = self;
    self.leftTAbelView.dataSource = self;
    self.leftTAbelView.backgroundColor = [UIColor colorWithWhite:0.957 alpha:1.000];
    
    [self.rightTAbelView registerNib:[UINib nibWithNibName:rightCellIdentifier bundle:nil] forCellReuseIdentifier:rightCellIdentifier];
    self.rightTAbelView.delegate = self;
    self.rightTAbelView.dataSource = self;
    
    _searchField.layer.cornerRadius = 4*VerticalRatio();
    _searchField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 5, 1)];
    _searchField.leftViewMode = UITextFieldViewModeAlways;
    _searchField.delegate = self;
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark - 搜索
- (IBAction)search:(id)sender {
    if (_searchField.hidden == YES) {
        _searchField.hidden = NO;
    }else{
        if (_searchField.text.length>0) {
            [_searchField resignFirstResponder];
            [self.rightTAbelView.header beginRefreshing];
        }else{
            _searchField.hidden = YES;
        }
    }
}

#pragma mark - 获取学校所属区域
-(void)area{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_sysAreaList withHttpType:@"POST" withTag:JY_JY_sysAreaList];
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.rightTAbelView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.rightTAbelView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self schoolList];
        });
        
    }];
    // 马上进入刷新状态
    [self.rightTAbelView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{

    if (_rightArray.count == _totle) {
        [self.rightTAbelView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self schoolList];
        });
    }
    
}

#pragma mark - 获取学校列表
- (void)schoolList {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    if (_msdtId.length > 0) {
        [dic setObject:_msdtId forKey:@"mallStoreDevelperTypeId"];
    }
    if (_serachStr > 0) {
        [dic setObject:_serachStr forKey:@"msdeName"];
    }
    if (_searchField.text.length > 0) {
        [dic setObject:_searchField.text forKey:@"msdeName"];
    }
    if (_count != 0) {
        [dic setObject:_AId forKey:@"sysAreaId"];
    }
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"lat"] forKey:@"lat"];
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"lng"] forKey:@"lng"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallStoreDeveloperList withHttpType:@"POST" withTag:JY_JY_mallStoreDeveloperList];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self hideKeyBoard];
    [self.rightTAbelView.header beginRefreshing];
    return YES;
}

#pragma mark - <UITableViewDelegate && UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == _leftTAbelView) {
        return self.leftArray.count;
    } else {
        return self.rightArray.count;
    }
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _leftTAbelView) {
        
        return 45*VerticalRatio();
    } else {
    
        return 90*VerticalRatio();
    }
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == _leftTAbelView) {
        AreaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:leftCellIdentifier];
        
        if (cell == nil) {
            cell= [[AreaTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:leftCellIdentifier];
        }
        
        
        cell.backgroundColor = [UIColor colorWithWhite:0.957 alpha:1.000];
        cell.label.textColor = [UIColor colorWithWhite:0.290 alpha:1.000];
        if (_count == indexPath.row) {
            cell.backgroundColor = [UIColor whiteColor];
            cell.label.textColor = [UIColor colorWithRed:0.086 green:0.306 blue:0.529 alpha:1.000];
        }
        cell.label.frame = flexibleFrame(CGRectMake(3, 11, 63, 0), NO);
        cell.label.numberOfLines = 0;
        cell.label.text = [NSString stringWithFormat:@"%@",self.leftArray[indexPath.row][@"AName"]];
        [cell.label sizeToFit];
        cell.label.center = CGPointMake(35*VerticalRatio(), 23*VerticalRatio());
        
        return cell;
        
    } else {
        
        SchoolTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:rightCellIdentifier];
        if (cell == nil) {
            cell= [[SchoolTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:rightCellIdentifier];
        }
            
        NSString *image = [NSString stringWithFormat:@"%@",self.rightArray[indexPath.row][@"msdeImage"]];
        if (image && image.length>0 && ![self.rightArray[indexPath.row][@"msdeImage"] isEqual:[NSNull null]]) {
            [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        cell.titleLabel.text = [NSString stringWithFormat:@"%@",self.rightArray[indexPath.row][@"msdeName"]];
        cell.detailLabel.text = [NSString stringWithFormat:@"%@",self.rightArray[indexPath.row][@"msdeContent"]];
        
        CGFloat distance = [self.rightArray[indexPath.row][@"distance"]floatValue];
        if (distance<1000) {
            [cell.areaButton setTitle:[NSString stringWithFormat:@" 距离%dm",(NSInteger)distance] forState:UIControlStateNormal];
        }else{
            [cell.areaButton setTitle:[NSString stringWithFormat:@" 距离%.1fkm",distance/1000] forState:UIControlStateNormal];
        }
        
        return cell;
    }
        
    
    
}


//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _leftTAbelView) {
        _count = indexPath.row;
        _AId = [NSString stringWithFormat:@"%@",_leftArray[indexPath.row][@"AId"]];
        [self.rightTAbelView.header beginRefreshing];
        [self.leftTAbelView reloadData];
        [self.rightTAbelView reloadData];
    } else {

            
        //学校详情
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"SchoolStoryboard" bundle:nil];
        SchoolProfileViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"SchoolProfile"];
        
        page.schoolId = _rightArray[indexPath.row][@"msdeId"];
        page.backBlock = ^(){};
        [[Common getNavigation] pushViewController:page];


    }
    
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_rightTAbelView.header endRefreshing];
    [_rightTAbelView.header endRefreshing];
    if (tag==JY_JY_sysAreaList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            self.leftArray = [NSMutableArray array];
            self.leftArray = database[@"result"];
            NSDictionary *dic =@{@"AName":@"全部区域"};
            [self.leftArray insertObject:dic atIndex:0];
            [self.leftTAbelView reloadData];
        }
    } else if (tag==JY_JY_mallStoreDeveloperList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.rightTAbelView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.rightTAbelView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.rightArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.rightArray addObject:entity];
                }
                [_rightTAbelView reloadData];
                
            });        }
    }
        

}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_rightTAbelView.header endRefreshing];
    [_rightTAbelView.header endRefreshing];
    [self dismissWaitDialog];
    
}

@end
